<template>
  <div class="tags">
    <el-tag style="margin-right: 10px" :key="tag.primaryKey" v-for="tag in tagStaffListChain" closable @close="tagDeleteChain(tag)" :disable-transitions="false">
      {{ tag.tagName }}
    </el-tag>
    <span v-if="!isAddTag" style="display: inline-block; width: 120px">
      <el-select style="width: 100%" size="small" v-model="tagsValue" remote @change="changeTag" placeholder="请选择标签" :loading="loading">
        <el-option v-for="item in tagList" :key="item.primaryKey" :label="item.tagName" :value="item.primaryKey"> </el-option>
      </el-select>
    </span>

    <el-button icon="el-icon-plus" size="small" circle v-if="isAddTag" @click="isAddTag = false"></el-button>
  </div>
</template>
<script>
  import { tagList, tagCreateChain, tagListChain, tagDeleteChain } from '../../../api/tag';
  export default {
    props: {
      primaryKey: {
        type: String,
        default: function () {
          return '';
        },
      },
    },

    data() {
      return {
        isAddTag: true,
        tagList: [],
        tagStaffListChain: [],
        tagsValue: [],
        loading: false,
      };
    },
    methods: {
      // 删除结构标签关系
      async tagDeleteChain(val) {
        await this.$confirm('此操作将删除标签, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        this.isAddTag = true;
        let primaryKey = val.primaryKey;
        await tagDeleteChain(primaryKey);
        this.tagListChain();
      },
      // 结构标签关系列表
      async tagListChain() {
        let getChainList = {};
        getChainList.targetType = 2;
        getChainList.targetKey = this.primaryKey;
        let { rows } = await tagListChain(getChainList);
        this.tagStaffListChain = rows;
      },
      // 添加员工标签关系
      async tagCreateChain(val) {
        let tagAddChain = {};
        tagAddChain.targetType = 2;
        tagAddChain.tagKey = val;
        tagAddChain.targetKey = this.primaryKey;
        await tagCreateChain(tagAddChain);
        this.tagsValue = '';
        this.tagListChain();
      },
      changeTag(val) {
        let flag = this.tagStaffListChain.some(item => {
          return item.tagKey == val;
        });
        if (flag) {
          this.$message.warning('添加标签已存在');
          this.tagsValue = '';
          this.isAddTag = !this.isAddTag;
        } else {
          this.tagCreateChain(val);
          this.isAddTag = !this.isAddTag;
        }
      },
      // 获取结构类型标签列表
      async getStaffTagsList() {
        let { rows, total } = await tagList({ tagType: 2 });
        this.tagList = rows;
      },
    },
    created() {
      this.getStaffTagsList();
      this.tagListChain();
    },
  };
</script>
